#!/bin/bash -e

TOP_DIR=$(pwd)
ROOTFS_PATH=$TOP_DIR

echo Making rootfs!

ROOTFSIMAGE=$TOP_DIR/rootfs.img
EXTRA_SIZE_MB=300

sudo ./mk-clean.sh

source ./mk-rootfs.sh arch=arm64 debian-version=bullseye host-name="HDC" chip=rk3399

if [ ! -f rootfs.tmp ]; then 
	touch rootfs.tmp
fi
P_OLD_MD5=$(cat rootfs.tmp | grep "pack" | awk -F ' ' '{print$2}')
I_OLD_MD5=$(cat rootfs.tmp | grep "init" | awk -F ' ' '{print$2}')
B_OLD_MD5=$(cat rootfs.tmp | grep "live" | awk -F ' ' '{print$2}')
C_OLD_MD5=$(cat rootfs.tmp | grep "customs" | awk -F ' ' '{print$2}')

P_NEW_MD5=$(md5sum customs/packes.list.tmp | awk -F ' ' '{print$1}')
I_NEW_MD5=$(md5sum customs/inits/scripts.tmp | awk -F ' ' '{print$1}')
B_NEW_MD5=$(md5sum customs/live/scripts.tmp | awk -F ' ' '{print$1}')
C_NEW_MD5=$(md5sum customs.tmp | awk -F ' ' '{print$1}')

if [ "$P_OLD_MD5" != "$P_NEW_MD5" ] || [ "$I_OLD_MD5" != "$I_NEW_MD5" ] || [ "$B_OLD_MD5" != "$B_NEW_MD5" ] || [ "$C_OLD_MD5" != "$C_NEW_MD5" ]; then 
	echo "I: 打包文件系统"
	IMAGE_SIZE_MB=$(expr $(echo $(sudo du -sh -m $(realpath "$ROOTFS_PATH") | cut -f1) + ${EXTRA_SIZE_MB}))

	# 删除历史镜像
	if [ -e ${ROOTFSIMAGE} ]; then
		rm ${ROOTFSIMAGE}
	fi

	# 生成IMG镜像文件
	dd if=/dev/zero of=${ROOTFSIMAGE} bs=1M count=0 seek=${IMAGE_SIZE_MB} &> /dev/null

	sudo mkfs.ext4 -d ${ROOTFS_PATH} ${ROOTFSIMAGE} &> /dev/null

	echo "pack $P_NEW_MD5" > rootfs.tmp
	echo "init $I_NEW_MD5" >> rootfs.tmp
	echo "live $B_NEW_MD5" >> rootfs.tmp
	echo "customs $C_NEW_MD5" >> rootfs.tmp

	echo Rootfs Image: ${ROOTFSIMAGE}
else
	echo "I: 系统未更新"
fi
